﻿using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using static System.Windows.Forms.VisualStyles.VisualStyleElement;

namespace YGBookmark.Models
{
    /// <summary>
    /// 书签实体模型（包含数据验证逻辑）
    /// </summary>
    [Table("Bookmarks")]
    public class Bookmark
    {
        private const int SummaryPreviewLength = 100;
        private const string DefaultCoverImage = "https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png";

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long Id { get; set; }

        [Required(ErrorMessage = "URL不能为空")]
        [StringLength(500, ErrorMessage = "URL长度不能超过500字符")]
        [RegularExpression(@"^(http|https)://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?$",
            ErrorMessage = "URL格式不正确")]
        public string Url { get; set; }

        [Required(ErrorMessage = "标题不能为空")]
        [StringLength(200, ErrorMessage = "标题长度不能超过200字符")]
        public string Title { get; set; }

        [StringLength(1000, ErrorMessage = "摘要长度不能超过1000字符")]
        public string Summary { get; set; }

        [StringLength(500, ErrorMessage = "封面图路径过长")]
        public string CoverImage { get; set; } = DefaultCoverImage;

        [StringLength(2000, ErrorMessage = "备注内容过长")]
        public string Remark { get; set; }

        [Required]
        [DataType(DataType.DateTime)]
        public DateTime CreateTime { get; set; } = DateTime.Now;

        // 导航属性
        public virtual ICollection<BookmarkTag> BookmarkTags { get; set; } = new List<BookmarkTag>();

        /// <summary>
        /// 无参构造函数（ORM需要）
        /// </summary>
        public Bookmark() { }

        /// <summary>
        /// 创建新书签的构造函数
        /// </summary>
        public Bookmark(string url, string title)
        {
            Url = url?.Trim() ?? throw new ArgumentNullException(nameof(url));
            Title = title?.Trim() ?? throw new ArgumentNullException(nameof(title));
        }

        /// <summary>
        /// 获取摘要预览（前100字符）
        /// </summary>
        [NotMapped]
        public string ShortSummary =>
            string.IsNullOrEmpty(Summary)
                ? string.Empty
                : Summary.Length > SummaryPreviewLength
                    ? $"{Summary.Substring(0, SummaryPreviewLength)}..."
                    : Summary;

        /// <summary>
        /// 验证封面图是否存在（虚拟方法供扩展）
        /// </summary>
        public virtual bool CoverImageExists() =>
            !string.IsNullOrWhiteSpace(CoverImage) &&
            (CoverImage.StartsWith("http", StringComparison.OrdinalIgnoreCase) ||
             File.Exists(CoverImage));

        /// <summary>
        /// 添加关联标签
        /// </summary>
        public void AddTag(Tag tag)
        {
            if (tag == null) throw new ArgumentNullException(nameof(tag));
            BookmarkTags.Add(new BookmarkTag { BookmarkId = Id, TagId = tag.Id });
        }

        /// <summary>
        /// 移除关联标签
        /// </summary>
        public void RemoveTag(Tag tag)
        {
            if (tag == null) throw new ArgumentNullException(nameof(tag));
            var bookmarkTag = BookmarkTags.FirstOrDefault(bt => bt.TagId == tag.Id);
            if (bookmarkTag != null)
            {
                BookmarkTags.Remove(bookmarkTag);
            }
        }

        public override string ToString() =>
            $"{Title} ({Url}) @ {CreateTime:yyyy-MM-dd HH:mm}";


        #region 1

        /// <summary>
        /// 标签名称集合（逗号分隔，非数据库直接映射字段）
        /// </summary>
        [NotMapped]  // 表示该属性不直接映射到数据库字段
        public string Tags { get; set; }

        #endregion 1

    }
}